import { Session, Local } from '/@/utils/storage';
import { reshToken } from '/@/api/login/index';

/**
 * 通过 refreshToken函数 刷新 token
 */
let promise: Promise<boolean> | null = null;

export function refreshToken(): Promise<boolean> {
	if (promise) return promise;

	promise = (async () => {
		try {
			const res = await reshToken();
			let tokenStatus = false;
			if (res.code == 200) {
				Local.set('token', res.data.accesstoken);
				Local.set('refreshToken', res.data.refreshToken);
				tokenStatus = true;
				Local.set('userInfo', res.data);
			} else if (res.code == -3) {
				tokenStatus = false;
			}

			// 返回是否刷新成功
			return tokenStatus;
		} catch (error) {
			console.error('Error refreshing token:', error);
			Session.clear(); // 清除浏览器全部临时缓存
			Local.clear(); // 清除浏览器全部临时缓存
			window.location.href = '/'; // 去登录页
			window.location.reload();
			return false; // 如果出错，返回 false
		} finally {
			promise = null; // 清空 promise
		}
	})();

	return promise;
}
